package com.cb2.algorithm.leetcode;

/**
 * <a href="https://leetcode.cn/problems/squares-of-a-sorted-array">有序数组的平方(Squares of a Sorted Array)</a>
 * <p>给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 *  示例 1：
 *      输入：nums = [-4,-1,0,3,10]
 *      输出：[0,1,9,16,100]
 *      解释：平方后，数组变为 [16,1,0,9,100]
 *      排序后，数组变为 [0,1,9,16,100]
 *
 * 示例 2：
 *      输入：nums = [-7,-3,2,3,11]
 *      输出：[4,9,9,49,121]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 * <ul>
 *  <li>1 <= nums.length <= 10^4</li>
 *  <li>-10^4 <= nums[i] <= 10^4</li>
 *  <li>nums 已按 非递减顺序 排序</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2025/2/6 15:54
 */
public class LC0977SquaresOfSortedArray_S {
    static class Solution {
        public int[] sortedSquares(int[] nums) {
            int[] res = new int[nums.length];
            int idx = nums.length - 1;

            int left = 0;
            int right = nums.length - 1;
            while (left <= right) {
                int target;
                if (Math.abs(nums[left]) <= Math.abs(nums[right])) {
                    target = Math.abs(nums[right--]);
                } else {
                    target = Math.abs(nums[left++]);
                }
                res[idx--] = target * target;
            }
            return res;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Printer.printArrayInt(solution.sortedSquares(new int[]{-4, -1, 0, 3, 10}));
        Printer.printArrayInt(solution.sortedSquares(new int[]{-7, -3, 2, 3, 11}));
        Printer.printArrayInt(solution.sortedSquares(new int[]{1}));
        Printer.printArrayInt(solution.sortedSquares(new int[]{-5, -3, -2, -1}));
    }
}
